package _7_io_socket_http;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

/**
 * Created by bpzj on 8/29/2018.
 */
public class Base {

    @Test
    public void getLocalHostInetAddress() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String hostName = address.getHostName();            // 获取计算机名
            String hostAddress = address.getHostAddress();      // 获取IP地址
            System.out.println(hostAddress);
            byte[] bytes = address.getAddress();    // 获取字节数组形式的IP地址,以点分隔的四部分
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    //使用URL读取网页内容
    @Test
    public void getInputStreamBuUrl() throws MalformedURLException {
        //创建一个URL实例
        // URL url = new URL("http://120.79.47.191");
        URL url = new URL("http://www.baidu.com");
        try (
            InputStream is = url.openStream();
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); //将字节输入流转换为字符输入流,如果不指定编码，中文可能会出现乱码
            BufferedReader br =new BufferedReader(isr)   //为字符输入流添加缓冲，提高读取效率
        ) {
            String data = br.readLine();//读取数据
            while (data != null) {
                System.out.println(data);//输出数据
                data = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
